

/**
 * 非微信小程序只有 开发版 和 正式版
 * develop  开发版
 * trial	  体验版
 * release	正式版
 */
export type EnvVersion = 'develop' | 'trial' | 'release';
type EnvTYLE =
  | 'ICON_URL'
  | 'BASE_URL'
  | 'H5_BASE_URL'
  | 'CLOUD_SCHOOL'
  | 'REQUEST_FILE_SERVER'
  | 'CDN_IMG_HEAD'
  | 'CDN_IMG_COMPRESSRATE'
  | 'SUBSCRIBEMSG_TEMPIDS';

export function useEnv() {
  //  高凉好礼 / 六度 / 会帮云 强制为测试环境
  const testAppId = ['wxb7f1b329b932f294', 'wxca9c31ea5e422e78', 'wx9e61f4c42841f164']

  const env = import.meta.env;

  const envObj: { [x: string]: string } = {};

  let envVersion: EnvVersion;

  // #ifndef MP-WEIXIN
  envVersion = env.MODE === 'development' ? 'develop' : 'release';
  // #endif

  // #ifdef MP-WEIXIN
  const { miniProgram } = uni.getAccountInfoSync();
  envVersion = miniProgram?.envVersion;
  // #endif

  Object.keys(env).forEach((key) => {
    let item: any[] = key.split('_');
    if (item[0] === 'UNIAPP') {
      item.splice(0, 1);
      const envVer = item[0].toLocaleLowerCase() as string
      if (['develop', 'trial', 'release'].includes(envVer)) {
        if (envVer === envVersion) {
          item.splice(0, 1);
          // #ifdef MP-WEIXIN
          if (key.includes(`${envVer.toLocaleUpperCase()}_BASE_URL`)) {
            const appid = miniProgram.appId;
            envObj[item.join('_') as string] = env[testAppId.includes(appid) ? 'UNIAPP_DEVELOP_BASE_URL' : 'UNIAPP_RELEASE_BASE_URL']
          } else {
            envObj[item.join('_') as string] = env[key] as string;
          }
          // #endif
          // #ifndef MP-WEIXIN
          envObj[item.join('_') as string] = env[key] as string;
          // #endif
        }
      } else {
        envObj[item.join('_') as string] = env[key] as string;
      }
    }
  });

  /**
   * 获取环境变量数据
   * @param type
   * @returns
   */
  function getEnv(type: EnvTYLE) {
    return envObj[type]
  }

  /**
   * 应用是否运行在生产环境
   * @returns boolean
   */
  function isProdMode() {
    return env.PROD;
  }

  /**
   * 应用是否运行在开发环境
   * @returns boolean
   */
  function isDevMode() {
    return env.DEV;
  }

  /** 当前是否是测试环境 (指定小程序) */
  function isTestEnv() {
    return envVersion !== 'release'
  }

  return {
    envVersion,
    getEnv,
    isProdMode,
    isDevMode,
    isTestEnv,
  };
}
